//
//  MTAccountController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/8.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTAccountController: BaseViewController {
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    private let disposeBag = DisposeBag()
    
    var model: MineAccountModel? {
        didSet {
            guard let model = model else { return }
            moneylabel.text = "\(model.ticketAmount)"
            moneyArr.append(model.sendGiftAmount)
            moneyArr.append(model.sendRedPacketAmount)
            tableView.reloadData()
        }
    }
    
    lazy var moneyArr: [Int] = {
        return []
    }()

    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(AccountListCell.self, forCellReuseIdentifier: AccountListCell.reuseIdentity())
        table.separatorInset = UIEdgeInsets.zero
        table.tableFooterView = UIView()
        return table
    }()
    
    lazy var moneylabel: UILabel = {
        let moneylabel = UILabel()
        moneylabel.textColor = .white
        moneylabel.font = PingFangSCSemiboldFont(20)
        return moneylabel
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        querySendStatics()
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        title = "我的账户"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("充值记录", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(accountController(didClickRecordtButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

extension MTAccountController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

extension MTAccountController {
    private func querySendStatics() {
        provider.rx.requestResult(.sendStatics).subscribe(onNext: { [weak self] (result: Result<MineAccountResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let result = response.result {
                        weakSelf.model = result
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: globalDisposedBag)
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTAccountController {
    
    private func accountController(didClickRecordtButton sender: UIButton) {
        navigationController?.pushViewController(MTTopUpHistoryListController(), animated: true)
    }
    
    private func accountController(didClickRechargeDiamondButton sender: UIButton) {
        if UserDefaults.AppValidate.isValidate.storedBool == false {
            let c = MTPaymentViewController()
            self.navigationController?.pushViewController(c, animated: true)
        } else {
            let c = MTInAppPurchasesViewController()
            self.navigationController?.pushViewController(c, animated: true)
        }
    }
}

extension MTAccountController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AccountListCell.reuseIdentity(), for: indexPath) as! AccountListCell
        cell.titleStr = indexPath.row == 0 ? "我送出的礼物" : "我送出的红包"
        cell.selectionStyle = .none
        if moneyArr.count > indexPath.row {
            cell.valueStr = "\(moneyArr[indexPath.row])"
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            let vc = MTGiftListController()
            vc.isSend = true
            navigationController?.pushViewController(vc, animated: true)
            
        } else {
            let vc = MTRedPacketListController()
            vc.isSend = true
            navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        let amountlabel = UILabel()
        amountlabel.text = "帐户当前总额"
        amountlabel.textColor = UIColor(hex:0x9b9b9b)
        amountlabel.font = PingFangSCMediumFont(12)
        view.addSubview(amountlabel)
        view.addSubview(moneylabel)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "dimond")
        view.addSubview(imageView)
        let topupBtn = UIButton()
        topupBtn.backgroundColor = UIColor(hex:0xffc000)
        topupBtn.setTitle("充值", for: .normal)
        topupBtn.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        topupBtn.titleLabel?.font = PingFangSCSemiboldFont(12)
        topupBtn.layer.cornerRadius = 12
        topupBtn.adjustsImageWhenHighlighted = false
        topupBtn.addTarget(self, action: #selector(accountController(didClickRechargeDiamondButton:)), for: .touchUpInside)
        view.addSubview(topupBtn)
        
        amountlabel.snp.makeConstraints { (make) in
            make.top.left.equalTo(view).offset(20)
        }
        
        moneylabel.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.top.equalTo(amountlabel.snp.bottom)
        }
        
        imageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(moneylabel)
            make.left.equalTo(moneylabel.snp.right).offset(4)
            make.width.height.equalTo(24)
        }
        topupBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.right.equalTo(view).offset(-20)
            make.width.equalTo(64)
            make.height.equalTo(24)
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
